from app.models.user import User
from app.extensions import db
from werkzeug.security import generate_password_hash
from datetime import datetime, timezone


class UserService:
    """用户服务类，处理用户相关的业务逻辑"""
    
    @staticmethod
    def get_all_users():
        """获取所有用户"""
        users = User.query.all()
        return [user.to_dict() for user in users]
    
    @staticmethod
    def get_user_by_id(user_id):
        """根据ID获取用户"""
        user = db.session.get(User, user_id)
        if user:
            return user.to_dict()
        return None
    
    @staticmethod
    def create_user(username, email, password):
        """创建新用户"""
        # 检查用户名是否已存在
        if User.query.filter_by(username=username).first():
            return None, "用户名已存在"
        
        # 检查邮箱是否已存在
        if User.query.filter_by(email=email).first():
            return None, "邮箱已存在"
        
        # 创建新用户
        user = User(
            username=username,
            email=email,
            password_hash=generate_password_hash(password),
            is_active=True,
            created_at=datetime.now(timezone.utc)
        )
        
        db.session.add(user)
        db.session.commit()
        
        return user.to_dict(), None
    
    @staticmethod
    def update_user(user_id, username=None, email=None, password=None, is_active=None):
        """更新用户信息"""
        user = db.session.get(User, user_id)
        if not user:
            return None, "用户不存在"
        
        # 更新用户名
        if username and username != user.username:
            # 检查用户名是否已存在
            if User.query.filter_by(username=username).first():
                return None, "用户名已存在"
            user.username = username
        
        # 更新邮箱
        if email and email != user.email:
            # 检查邮箱是否已存在
            if User.query.filter_by(email=email).first():
                return None, "邮箱已存在"
            user.email = email
        
        # 更新密码
        if password:
            user.password_hash = generate_password_hash(password)
        
        # 更新状态
        if is_active is not None:
            user.is_active = is_active
        
        user.updated_at = datetime.now(timezone.utc)
        
        db.session.commit()
        
        return user.to_dict(), None
    
    @staticmethod
    def delete_user(user_id):
        """删除用户"""
        user = db.session.get(User, user_id)
        if not user:
            return False, "用户不存在"
        
        db.session.delete(user)
        db.session.commit()
        
        return True, None